<template>
  <transition name="slide-fade">
    <div class="icons" v-show="visiable" @click="handleScrollTop">
      <!-- 需要显示的icon图标 -->
      <div class="menu">
        <q-icon :name="biRocket" color="white" size="18px"/>
      </div>
    </div>
  </transition>
</template>


<script setup lang='ts'>
import { defineProps, defineEmits, defineExpose } from 'vue'

defineProps({
})

const emit = defineEmits([])

defineExpose({})

import { biRocket } from '@quasar/extras/bootstrap-icons'

import { ref, onMounted, onUnmounted } from 'vue'
const scrollTop = ref(0) // 距顶部距离
const visiable = ref(false) // 是否显示组件
let done = false // 是否停止帧函数

// 检测距离
function handleScroll() {
  scrollTop.value =
      window.pageYOffset ||
      document.documentElement.scrollTop ||
      document.body.scrollTop
  scrollTop.value > 1500 ? (visiable.value = true) : (visiable.value = false)
}

function step() {
  scrollTop.value <= 0 ? (done = true) : (done = false)
  window.scrollTo({
    top: (scrollTop.value -= 150)
  })
  if (!done) {
    window.requestAnimationFrame(step)
  }
}

// 返回顶部
function handleScrollTop() {
  // 下一次重绘之前更新动画帧所调用的函数 60次1秒
  // https://developer.mozilla.org/zh-CN/docs/Web/API/Window/requestAnimationFrame
  window.requestAnimationFrame(step)
}

// 设置监听与卸载
onMounted(() => {
  window.addEventListener('scroll', handleScroll)
})
onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
})

</script>

<style scoped lang='less'>
.icons {
  position: fixed;
  right: 3rem;
  bottom: 7rem;
  width: 3rem;
  padding: 8px;
  background-color: #26A69A;
  box-shadow: 0 0.25rem 0.625rem 0 hsla(220, 4%, 56%, 0.2);
  cursor: pointer;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  .menu{
    padding: 5px 20px 5px 20px
  }
}
.icons > .icon {
  color: #1abc9c;
}
.icons:hover > .icon {
  display: none;
}
</style>